"""
高德地图工具使用示例
展示如何使用高德地图工具进行路线规划
"""

import sys
import os
import logging

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from tools.amap_tool import AmapTool, TravelMode
from utils.config import Config

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def demo_geocoding():
    """演示地理编码功能"""
    logger.info("=" * 50)
    logger.info("地理编码功能演示")
    logger.info("=" * 50)
    
    amap_tool = AmapTool()
    
    # 测试地址列表
    addresses = [
        {"address": "天府广场", "city": "成都"},
        {"address": "春熙路", "city": "成都"},
        {"address": "宽窄巷子", "city": "成都"},
        {"address": "都江堰景区", "city": "成都"}
    ]
    
    for addr_info in addresses:
        logger.info(f"\n查询地址: {addr_info['address']}")
        logger.info("-" * 30)
        
        result = amap_tool.geocode_address(addr_info['address'], addr_info['city'])
        
        if 'error' in result:
            logger.error(f"地理编码失败: {result['error']}")
        else:
            logger.info(f"✓ 完整地址: {result['address']}")
            logger.info(f"✓ 坐标: {result['longitude']}, {result['latitude']}")
            logger.info(f"✓ 位置: {result['province']} {result['city']} {result['district']}")

def demo_route_planning():
    """演示路线规划功能"""
    logger.info("\n" + "=" * 50)
    logger.info("路线规划功能演示")
    logger.info("=" * 50)
    
    amap_tool = AmapTool()
    
    # 路线规划示例
    routes = [
        {
            "name": "天府广场到春熙路步行",
            "origin": "天府广场",
            "destination": "春熙路",
            "mode": TravelMode.WALKING,
            "city": "成都"
        },
        {
            "name": "天府广场到宽窄巷子骑车",
            "origin": "天府广场",
            "destination": "宽窄巷子",
            "mode": TravelMode.BICYCLING,
            "city": "成都"
        },
        {
            "name": "天府广场到双流机场公共交通",
            "origin": "天府广场",
            "destination": "成都双流国际机场",
            "mode": TravelMode.TRANSIT,
            "city": "成都"
        },
        {
            "name": "天府广场到都江堰自驾",
            "origin": "天府广场",
            "destination": "都江堰景区",
            "mode": TravelMode.DRIVING,
            "city": "成都"
        }
    ]
    
    for route in routes:
        logger.info(f"\n{route['name']}")
        logger.info("-" * 40)
        
        result = amap_tool.plan_route(
            route['origin'],
            route['destination'],
            route['mode'],
            route.get('city')
        )
        
        if 'error' in result:
            logger.error(f"路线规划失败: {result['error']}")
        else:
            # 显示路线摘要
            summary = amap_tool.get_route_summary(result)
            logger.info(summary)
            
            # 显示详细步骤（仅显示前3步）
            if route['mode'] in [TravelMode.WALKING, TravelMode.BICYCLING]:
                steps = result.get('steps', [])
                if steps:
                    logger.info("\n详细步骤（前3步）:")
                    for i, step in enumerate(steps[:3], 1):
                        logger.info(f"  {i}. {step['instruction']}")
                        logger.info(f"     距离: {step['distance']}米, 时间: {step['duration']}秒")
            
            elif route['mode'] == TravelMode.TRANSIT:
                plans = result.get('plans', [])
                if plans:
                    plan = plans[0]
                    logger.info(f"\n推荐方案:")
                    logger.info(f"  费用: {plan['cost']}元")
                    logger.info(f"  时间: {plan['duration']}秒")
                    logger.info(f"  步行距离: {plan['walking_distance']}米")
            
            elif route['mode'] == TravelMode.DRIVING:
                plans = result.get('plans', [])
                if plans:
                    plan = plans[0]
                    logger.info(f"\n推荐方案:")
                    logger.info(f"  距离: {plan['distance']}米")
                    logger.info(f"  时间: {plan['duration']}秒")
                    logger.info(f"  过路费: {plan['tolls']}元")
                    logger.info(f"  红绿灯: {plan['traffic_lights']}个")

def demo_batch_planning():
    """演示批量路线规划"""
    logger.info("\n" + "=" * 50)
    logger.info("批量路线规划演示")
    logger.info("=" * 50)
    
    amap_tool = AmapTool()
    
    # 批量路线规划请求
    batch_requests = [
        {
            "origin": "天府广场",
            "destination": "春熙路",
            "mode": "walking",
            "city": "成都"
        },
        {
            "origin": "天府广场",
            "destination": "宽窄巷子",
            "mode": "bicycling",
            "city": "成都"
        },
        {
            "origin": "天府广场",
            "destination": "成都双流国际机场",
            "mode": "transit",
            "city": "成都"
        },
        {
            "origin": "天府广场",
            "destination": "都江堰景区",
            "mode": "driving",
            "city": "成都"
        }
    ]
    
    logger.info("开始批量路线规划...")
    results = amap_tool.batch_plan_routes(batch_requests)
    
    logger.info(f"\n批量规划完成，共处理 {len(results)} 个请求")
    logger.info("-" * 40)
    
    for i, (request, result) in enumerate(zip(batch_requests, results), 1):
        logger.info(f"\n请求 {i}: {request['origin']} -> {request['destination']} ({request['mode']})")
        
        if 'error' in result:
            logger.error(f"  ✗ 失败: {result['error']}")
        else:
            summary = amap_tool.get_route_summary(result)
            # 只显示摘要的第一行（出行方式、起点、终点）
            summary_lines = summary.split('\n')
            logger.info(f"  ✓ 成功: {summary_lines[0]}")
            logger.info(f"    {summary_lines[1]}")
            logger.info(f"    {summary_lines[2]}")

def demo_route_comparison():
    """演示不同出行方式的路线对比"""
    logger.info("\n" + "=" * 50)
    logger.info("出行方式对比演示")
    logger.info("=" * 50)
    
    amap_tool = AmapTool()
    
    origin = "天府广场"
    destination = "春熙路"
    city = "成都"
    
    modes = [
        TravelMode.WALKING,
        TravelMode.BICYCLING,
        TravelMode.TRANSIT,
        TravelMode.DRIVING
    ]
    
    logger.info(f"路线对比: {origin} -> {destination}")
    logger.info("-" * 40)
    
    results = []
    
    for mode in modes:
        logger.info(f"\n正在规划{mode.value}路线...")
        
        result = amap_tool.plan_route(origin, destination, mode, city)
        
        if 'error' in result:
            logger.error(f"{mode.value}路线规划失败: {result['error']}")
        else:
            results.append((mode, result))
    
    # 显示对比结果
    if results:
        logger.info(f"\n路线对比结果:")
        logger.info("-" * 40)
        
        for mode, result in results:
            summary = result.get('summary', {})
            mode_name = amap_tool._get_mode_display_name(mode.value)
            
            logger.info(f"\n{mode_name}:")
            
            if mode in [TravelMode.WALKING, TravelMode.BICYCLING]:
                logger.info(f"  距离: {summary.get('total_distance', '未知')}")
                logger.info(f"  时间: {summary.get('total_duration', '未知')}")
            elif mode == TravelMode.TRANSIT:
                logger.info(f"  时间: {summary.get('total_duration', '未知')}")
                logger.info(f"  费用: {summary.get('total_cost', '未知')}")
                logger.info(f"  步行: {summary.get('walking_distance', '未知')}")
            elif mode == TravelMode.DRIVING:
                logger.info(f"  距离: {summary.get('total_distance', '未知')}")
                logger.info(f"  时间: {summary.get('total_duration', '未知')}")
                logger.info(f"  过路费: {summary.get('tolls', '未知')}")

def main():
    """主函数"""
    logger.info("高德地图工具使用示例")
    logger.info("=" * 60)
    
    try:
        # 验证配置
        Config.validate_amap_config()
        logger.info("✓ 高德地图配置验证通过")
        
        # 演示各项功能
        demo_geocoding()
        demo_route_planning()
        demo_batch_planning()
        demo_route_comparison()
        
        logger.info("\n" + "=" * 60)
        logger.info("示例演示完成！")
        
    except Exception as e:
        logger.error(f"示例运行出错: {str(e)}")
        logger.error("请确保已正确配置AMAP_API_KEY环境变量")

if __name__ == "__main__":
    main()
